package com.rocketmq.base.example.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import java.util.List;

public class OrderedProducer {
    public static void main(String[] args) throws Exception {
        //Instantiate with a producer group name.
        MQProducer producer = new DefaultMQProducer("order_producer_group_name");
        ((DefaultMQProducer) producer).setNamesrvAddr("192.168.1.221:9876");
        //Launch the instance.
        producer.start();
        String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
        // TopicTestjjj TagA KEY0 Hello RocketMQ 0 orderId 0
        // TopicTestjjj TagB KEY1 Hello RocketMQ 1 orderId 1
        // TopicTestjjj TagC KEY2 Hello RocketMQ 2 orderId 2
        // TopicTestjjj TagD KEY3 Hello RocketMQ 3 orderId 3
        // TopicTestjjj TagE KEY4 Hello RocketMQ 4 orderId 4
        // TopicTestjjj TagA KEY5 Hello RocketMQ 5 orderId 5
        // TopicTestjjj TagB KEY6 Hello RocketMQ 6 orderId 6
        // TopicTestjjj TagC KEY7 Hello RocketMQ 7 orderId 7
        // TopicTestjjj TagD KEY8 Hello RocketMQ 8 orderId 8
        // TopicTestjjj TagE KEY9 Hello RocketMQ 9 orderId 9
        // TopicTestjjj TagA KEY10 Hello RocketMQ 10 orderId 0
        for (int i = 0; i < 100; i++) {
            int orderId = i % 10;
            //Create a message instance, specifying topic, tag and message body.
            Message msg = new Message("TopicTestOrder", tags[i % tags.length], "KEY" + i,
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            /**
             * msg: 消息
             * selector 消息队列选择器
             * orderId : 业务标识 （队列的业务标识）
             */
            SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                /**
                 *
                 * @param mqs Topic下面的所有的队列
                 * @param msg 消息
                 * @param arg 业务标识  send方法的第三个参数 这个参数是数字，来明确是第几个队列
                 * @return
                 */
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    Integer id = (Integer) arg;
                    int index = id % mqs.size();
                    return mqs.get(index);
                }
            }, orderId);

            System.out.printf("%s%n", sendResult);
        }
        //server shutdown
        producer.shutdown();
    }
}
